
import { merge } from 'lodash'
import { Message } from 'element-ui'
import * as download from 'js-file-download'
import getFilename from './byteConvert'

function isUrl (string) {
  if (typeof string !== 'string') {
    return false
  }

  var match = string.match(/^(?:\w+:)?\/\/(\S+)$/)
  if (!match) {
    return false
  }

  var everythingAfterProtocol = match[1]
  if (!everythingAfterProtocol) {
    return false
  }

  if (
    /^localhost[\:?\d]*(?:[^\:?\d]\S*)?$/.test(everythingAfterProtocol) ||
    /^[^\s\.]+\.\S{2,}$/.test(everythingAfterProtocol)
  ) {
    return true
  }

  return false
}

function isJSON (str) {
  try {
    var obj = JSON.parse(str)
    if (obj && typeof obj === 'object') {
      return true
    }
  } catch (err) {}
  return false
}


export function downloadFile (res, fname) {

  if (isUrl(res) && fname) {
    // a链接下载文件
    var tempLink = document.createElement('a')
    tempLink.style.display = 'none'
    tempLink.href = res
    tempLink.setAttribute('download', fname)
    tempLink.setAttribute('target', '_blank')

    document.body.appendChild(tempLink)
    tempLink.click()

    // Fixes "webkit blob resource error 1"
    setTimeout(function () {
      document.body.removeChild(tempLink)
    }, 200)
    return
  }
  let nameStr, fileName
  if(!fname){
    try {
      // 获取header中的
      let array = res.response.headers['content-disposition'].split('fileName=')
      nameStr = array[array.length - 1]
      fileName = nameStr
    } catch {}
  } else{
    fileName = fname
  }


  let r = new TextDecoder().decode(new Uint8Array(res))
  if (isJSON(r)) {
    // json格式的 错误信息

    r = JSON.parse(r)
    console.log(r)
    Message({
      message: r.message,
      type: 'error',
      duration: 5 * 1000
    })
  } else {
    download(res, fileName)
  }
}

/**
 * @description:
 * @param {type} this.api.API_WEBAUDIT_UPLOADAUDITFILE_POST , {body:FormData}
 * @return {type} Promise pedding
 *
 *
 *
 * upload(api.API_WEBAUDIT_UPLOADAUDITFILE_POST, {body:fd}).then()
 */
export function uploadFile (api, options) {
  let opt = merge(
    {
      header: {
        'Content-Type': 'multipart/form-data'
      }
    },
    options
  )
  return api(opt)
}
